﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using SuperiorModel;
using SuperiorCommon;
using SuperiorShopBussinessService;
using Redis;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Drawing;

namespace Api.SuperiorShop.Controllers
{
    [ApiExceptionAttribute]
    public class ProductController : ApiControllerBase
    {
        private readonly IProductService _IProductService;
        private readonly ISetService _ISetService;
        private readonly IShopAppService _IShopAppService;

        public ProductController(IProductService IProductService, ISetService ISetService, IShopAppService IShopAppService)
        {
            _IProductService = IProductService;
            _ISetService = ISetService;
            _IShopAppService = IShopAppService;
        }
        protected override void Dispose(bool disposing)
        {
            this._IProductService.Dispose();
            this._ISetService.Dispose();
            base.Dispose(disposing);
        }
        // GET: Product


        /// <summary>
        ///获取分类目录集合数据
        /// </summary>
        /// <param name="spid"></param>
        /// <returns></returns>
        /// 
        [HttpGet]
        public ApiResultModel<object> GetMenuList(string said)
        {
            string _said = base.ValidataParms(said);
            if (_said == null)
                return Error("非法参数");
            Func<List<Api_MenuItemModel>> fucc = delegate ()
            {
                return _IProductService.Api_GetMenuList(_said.ToInt());
            };
            var res = DataIntegration.GetData<List<Api_MenuItemModel>>("GetMenuList_" + _said, fucc);
            return Success(res);
        }

        /// <summary>
        ///获取商品集合数据
        /// </summary>
        /// <param name="spid"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResultModel<object> GetProductList(Api_ProductListCriteria criteria)
        {
            string _spid = base.ValidataParms(criteria.Spid);
            if (_spid == null)
                return Error("非法参数");
            criteria.Spid = _spid;
            List<Api_ProductItem> res = null;
            if (string.IsNullOrEmpty(criteria.keyWord) && criteria.MenuId == 0)
            {
                Func<List<Api_ProductItem>> fucc = delegate ()
                {
                    return _IProductService.Api_GetProductList(criteria);
                };
                res = DataIntegration.GetData<List<Api_ProductItem>>("GetProductList_" + _spid + "_Offset_" + criteria.OffSet, fucc, 1);
            }
            else
            {
                res = _IProductService.Api_GetProductList(criteria);
            }

            return Success(res);
        }
        /// <summary>
        /// 获取商品详情
        /// </summary>
        /// <param name="id"></param>
        /// <param name="said"></param>
        /// <returns></returns>
        public ApiResultModel<object> GetProductDetail(string id, string said)
        {
            string _id = base.ValidataParms(id);
            if (_id == null)
                return Error("非法参数");
            string _shopAdminId = base.ValidataParms(said);
            if (_shopAdminId == null)
                return Error("非法参数");
            //读取商品主体
            Func<Api_ProductDetailModel> fucc = delegate ()
            {
                return _IProductService.Api_GetProduct(_id.ToInt());
            };
            var res = DataIntegration.GetData<Api_ProductDetailModel>("GetProductDetail_" + _id, fucc);
            //读运费
            Func<ShippingTemplateModel> fucc1 = delegate ()
            {
                return _ISetService.GetShippingTemplateModel(res.ShipTemplateId);
            };
            var shipmodel = DataIntegration.GetData<ShippingTemplateModel>("ShippingTemplateModel_" + res.ShipTemplateId, fucc1);
            //取出运费所有区域的子运费模板的最大金额和最小金额
            var _minAmount = shipmodel.Items.Min(p => p.FirstAmount);
            var _maxAmount = shipmodel.Items.Max(p => p.FirstAmount);
            res.ShipAmount = _minAmount + " - " + _maxAmount;
            //根据商品主体的sku类型，读取商品的sku数据
            if (res.CurrentSkuType == 1)
            {
                res.SkuManagerModel = _IProductService.GetProductSkuManagerModel(_shopAdminId.ToInt(), _id);//由于库存原因，商品SKU不走redis
            }
            else if (res.CurrentSkuType == 2)
            {
                res.SkuManagerModel = _IProductService.GetProductSkuManagerModel_AJAX(_shopAdminId.ToInt(), _id);
            }
            return Success(res);
        }
        /// <summary>
        /// 获取专场/专区数据模型
        /// </summary>
        /// <param name="said"></param>
        ///  <param name="type"></param>
        /// <returns></returns>
        public ApiResultModel<object> GetSpecialPlaceData(string said, int type = 1)
        {
            string _shopAdminId = base.ValidataParms(said);
            if (_shopAdminId == null)
                return Error("非法参数");
            //读取商品主体
            Func<List<SpecialPlaceModel>> fucc = delegate ()
            {
                return _IProductService.SpecialPlaceList(_shopAdminId.ToInt(),type);
            };
            var res = DataIntegration.GetData<List<SpecialPlaceModel>>("SpecialPlaceList" + _shopAdminId + "_" + type, fucc);
            return Success(res);
        }
        /// <summary>
        /// 生成商品详情海报
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResultModel<object> MobileQrCodeImage(Api_ProductQrImageParms model)
        {
            var _shopid = base.ValidataParms(model.ShopID);
            if (_shopid == null)
                return Error("非法参数");
            var cacheKey = "QrCode_Product_" + model.ProductId;
            var res = RedisManager.Get<string>(cacheKey);//小程序商品详情路径二维码base64字符串
            //object res = null;
            string base64img = "";
            if (res == null)
            {
                Func<ShopAppModel> fucc = delegate ()
                {
                    return _IShopAppService.GetShopAppModel(_shopid.ToInt());
                };
                var shopAppModel = DataIntegration.GetData<ShopAppModel>("GetShopAppModel_" + _shopid, fucc);
                if (shopAppModel == null)
                    return Error("获取店铺模型出错");

                string tokenJson = WeiXinHelper.GetAccessToken(shopAppModel.AppId, shopAppModel.AppSecret);
                LogManger.Instance.WriteLog("微信获取Accesstoken返回数据：" + tokenJson);
                JObject jo = JObject.Parse(tokenJson);
                string access_token = jo["access_token"].ToString();
                //直接请求二维码信息
                string path = "pages/product/detail?id=" + model.ProductId + "&said=" + shopAppModel.ShopAdminId;
                var ret = WeiXinHelper.GetQrCode(access_token, path, 90);
                //LogManger.Instance.WriteLog("微信获取二维码返回数据：" + ret);
                //存入redis
                RedisManager.Set<string>(cacheKey, Convert.ToBase64String(ret), DateTime.Now.AddMonths(15));
                res = Convert.ToBase64String(ret);
                base64img = Convert.ToBase64String(ret);
            }
            else
            {
                base64img = res.ToString();
            }
            //拼图
            //------
            var _fold = "qrproduct";
            var card_saveName = "qrp" + model.ProductId + ".jpg";
            var card_savePath = Path.Combine(ProductBannerUploader.Instance.TempPhysicalPath.Replace("Temp", _fold), card_saveName);

            string productname = "";
            string price = "";
            string productimgpath = "";
            string qrimgbase64 = "";

            productname = model.PECName;
            price = "￥" + model.PriceRanage;
            qrimgbase64 = base64img;
            //productimgpath = imgBase2 + "/" + model.ProductImage.Substring(model.ProductImage.IndexOf("uploadfile"));
            productimgpath = model.ProductImage;
            var logValue = new
            {
                productid = model.ProductId,
                productname = productname,
                price = model.PriceRanage,
                productimgpath = productimgpath
            };
            LogManger.Instance.WriteLog("QRProductImage：" + logValue.ToJson());

            // 生成二维码图片
            DrawQRImageService qrservice = new DrawQRImageService();
            Bitmap result_map = qrservice.QrProductImage(productname, price, productimgpath, qrimgbase64);
            // 名片存储地址
            result_map.Save(card_savePath, System.Drawing.Imaging.ImageFormat.Jpeg);

            //var ms_hd = new MemoryStream();
            //result_map.Save(ms_hd, System.Drawing.Imaging.ImageFormat.Png);

            var returnImgPath = ConfigSettings.Instance.ImageHost + "/" + _fold + "/" + card_saveName + "?r=" + new Random().Next(1, 10000);
            return Success(returnImgPath);
        }
    }
}